package com.spica.spicaschool.utils

import android.os.Handler
import android.os.Looper
import android.os.MessageQueue

object UiUtils {




  private fun isMainThread(): Boolean {
      return Looper.myLooper() != Looper.getMainLooper()
  }

    fun doMainThreadle(action: () -> Unit, timeout: Long? = null) {
        val handler = Handler(Looper.getMainLooper())
        val idleHandler = MessageQueue.IdleHandler {
            handler.removeCallbacksAndMessages(null)
            action()
            return@IdleHandler false
        }

        fun setupIdleHandler(queue: MessageQueue) {
            if (timeout != null) {
                handler.postDelayed(
                    {
                        queue.removeIdleHandler(idleHandler)
                        action()
                    },
                    timeout
                )
            }
            queue.addIdleHandler(idleHandler)
        }

        if (isMainThread()) {
            setupIdleHandler(Looper.myQueue())
        } else {
            setupIdleHandler(Looper.getMainLooper().queue)
        }
    }

}